package com.mililoan.console.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mililoan.common.bean.CommonResult;
import com.mililoan.common.bean.UserStatus;
import com.mililoan.common.constant.RightmrgGlobe;
import com.mililoan.common.utils.StackTraceUtil;
import com.mililoan.common.utils.Tool;
import com.mililoan.console.service.OnlineService;
import com.mililoan.console.tools.WebUtil;
import com.mililoan.model.system.Actor;
import com.mililoan.model.system.Department;
import com.mililoan.model.system.Menu;
import com.mililoan.model.system.User;
import com.mililoan.service.module.system.DepartmentBo;
import com.mililoan.service.module.system.MenuBo;
import com.mililoan.service.module.system.ParamBo;
import com.mililoan.service.module.system.UserBo;


@Controller
@Scope("prototype")
@RequestMapping("login")
public class LoginAction {
	private static Logger		LOGGER		= LoggerFactory.getLogger(LoginAction.class);	
	private final static String	NEEDCODE	= "needcode";	//是否需要验证码
	
	@Autowired
	private MenuBo				menuBo;
	@Autowired
	private UserBo				userBo;
//	@Autowired
//	private LogBo				logBo;
	@Autowired
	private DepartmentBo		departmentBo;
	@Autowired
	private ParamBo				paramBo;


	@RequestMapping("/init.do")
	public String init(Model model) {
		// 新增：只有参数配置为需要验证码的时候才验证
//		Param codetag = paramBo.getParamByName(NEEDCODE);
//		if (null != codetag && "1".equals(codetag.getParam())) {
//			model.addAttribute(NEEDCODE, "1");
//		} else {
//			model.addAttribute(NEEDCODE, "0");
//		}
		return "welcome/login";
	}

	@RequestMapping("/welcome.do")
	public String welcome(Model model) {
		return "welcome/welcome";
	}

	@RequestMapping("/in.do")
	@ResponseBody
	public CommonResult in(@RequestParam(required = false) String accounts,
			@RequestParam(required = false) String password, @RequestParam(required = false) String mycode,
			Model model) throws Exception {
		CommonResult commonResult = new CommonResult();
		commonResult.setMessage("登录成功");
		model.addAttribute(NEEDCODE, "0");
		User user = userBo.getUser(accounts, password);

		// 新增：只有参数配置为需要验证码的时候才验证
//		Param codetag = paramBo.getParamByName(NEEDCODE);
//		if (null != codetag && "1".equals(codetag.getParam())) {
//			model.addAttribute(NEEDCODE, "1");
//			User loguser = userBo.getUser(accounts);
//			if (loguser == null) {
//				commonResult.setMessage("您输入的用户名在系统中不存在");
//				commonResult.setResultCode(CommonResult.FAIL);
//			}
//			if (null == mycode || "".equals(mycode)) {
//				commonResult.setMessage("您输入的验证码不正确");
//				commonResult.setResultCode(CommonResult.FAIL);
//			} else {
//				boolean flag = userBo.checkCode(mycode, loguser.getMobile().trim());
//				if (!flag) {
//					commonResult.setMessage("您输入的验证码无效");
//					commonResult.setResultCode(CommonResult.FAIL);
//				} else {
//					boolean upflag = userBo.updateCode(mycode, loguser.getMobile().trim());
//					if (!upflag) {
//						LOGGER.info("更新验证码" + mycode + "失败！");
//					}
//				}
//			}
//		}

		if (null == user || user.getId()<=0) {
			LOGGER.info((accounts == null ? "" : accounts) + ",用户名或者密码错误！");
//			logBo.add(100, "用户名或者密码错误！" + (accounts == null ? "" : accounts), OpLog.FAIL);
			commonResult.setMessage("您输入的用户名或者密码错误!");
			commonResult.setResultCode(CommonResult.FAIL);
		} else {
			Department department = departmentBo.getDepartmentById(user.getDepartmentCode());
			HttpSession session = WebUtil.getThreadSession();

			session.setAttribute(RightmrgGlobe.SESSION_USER_KEY, user);// 设置session中的数据
			this.setFuns(user, session);
			this.setModules(department, session);

			// 置在线状态
			UserStatus status = new UserStatus();
			status.setUserid(user.getId());
			status.setUserName(user.getUserName());
			status.setLoginDate(new Date());
			status.setTouchDate(new Date());
			status.setSessionId(session.getId());
			OnlineService.putStatus(status, true);// 存储进在线人员列表

//			logBo.add(100, "成功登录管理端！", OpLog.SUCCESS);
			return commonResult;
		}
		return commonResult;
	}

	@RequestMapping("/getMenu.do")
	@ResponseBody
	public Menu getMenu() {
		Menu menu = null;
		if (WebUtil.getThreadSession().getAttribute(RightmrgGlobe.SESSION_MENU) == null) {
			menu = menuBo.getMenu(WebUtil.getActSet());
			WebUtil.getThreadSession().setAttribute(RightmrgGlobe.SESSION_MENU, menu);
		} else {
			menu = (Menu) WebUtil.getThreadSession().getAttribute(RightmrgGlobe.SESSION_MENU);
		}
		return menu;
	}

	/**
	 * 登出
	 */
	@RequestMapping("/off.do")
	public String off(HttpServletRequest request, Model model) {
		// 新增：只有参数配置为需要验证码的时候才验证
//		Param codetag = paramBo.getParamByName(NEEDCODE);
//		if (null != codetag && "1".equals(codetag.getParam())) {
//			model.addAttribute(NEEDCODE, "1");
//		} else {
//			model.addAttribute(NEEDCODE, "0");
//		}
		HttpSession session = request.getSession();
		User loginUser = (User) session.getAttribute(RightmrgGlobe.SESSION_USER_KEY);
		// 插入日志
		// 清除在线状态
		if (loginUser != null) {
			OnlineService.deleteStatus(loginUser.getId());
		}
		session.removeAttribute(RightmrgGlobe.SESSION_USER_KEY);
		session.removeAttribute(RightmrgGlobe.SESSION_USER_FUNS);
		session.removeAttribute(RightmrgGlobe.SESSION_DEP_MODULES);
		session.invalidate();// 销毁session
		return "welcome/login";
	}

	/**
	 * 加载用户权限
	 */
	private void setFuns(User user, HttpSession session) {
		HashSet<Integer> actSet = userBo.getUserActor(user);
		session.setAttribute(RightmrgGlobe.SESSION_USER_FUNS, actSet);
	}

	/**
	 * 加载部门模块
	 */
	@SuppressWarnings("unused")
	private void setModules(Department department, HttpSession session) {
		HashSet<Integer> depMods = new HashSet<Integer>();
		Integer[] arrayMods = department.getArrayMods();
		if (arrayMods != null && arrayMods.length > 0) {
			for (int i = 0; i < arrayMods.length; i++) {
				depMods.add(arrayMods[i]);
			}
		}
		session.setAttribute(RightmrgGlobe.SESSION_DEP_MODULES, depMods);
	}

//	@RequestMapping("getSmsCode.do")
//	@ResponseBody
//	public CommonResult getSmsCode(@RequestParam(required = false) String accounts) {
//		try {
//			if (accounts == null || "".equals(accounts)) {
//				return new CommonResult(CommonResult.FAIL, "用户名不正确");
//			}
//			User loginUser = userBo.getUser(accounts);
//			String mobile = loginUser.getMobile();
//			boolean pass = checkMobile(mobile);
//			if (!pass) {
//				return new CommonResult(CommonResult.FAIL, "该用户手机号无效，请联系管理员");
//			}
//			// 检查登陆次数
//			String ip = WebUtil.getRemoteAddress(WebUtil.getThreadRequest());
//			boolean countflag = userBo.checkCount(ip);
//			if (!countflag) {
//				return new CommonResult(CommonResult.FAIL, "失败超过6次，请1小时后再登录!");
//			}
//			// 含有有效期内的验证码
//			if (!checkMobile(mobile)) {
//				return new CommonResult(CommonResult.FAIL, "上一个验证码还未过期");
//			}
//
//			// 添加code到数据库
//			long code = System.currentTimeMillis() % 10000;
//			int addcodebak = userBo.addCode(String.valueOf(code), mobile, ip);
//			if (addcodebak == 0) {
//				return new CommonResult(CommonResult.FAIL, "验证码加入数据库异常");
//			}
//			return new CommonResult(CommonResult.SUCCESS, "短信发送成功!");
//		} catch (Exception e) {
//			LOGGER.error("短信发送失败:");
//			LOGGER.error(StackTraceUtil.getStackTrace(e));
//			return new CommonResult(CommonResult.FAIL, "短信发送失败!");
//		}
//	}

	/**
	 *
	 * @Title: toWorkbench
	 * @Description: 跳转到我的工作台
	 * @author YangChaofeng 2016年5月10日 下午3:27:27
	 * @return
	 */
	@RequestMapping("/toWorkbench.do")
	public String toWorkbench(@RequestParam(value = "flag", required = false) String flag, HttpServletRequest request,
			Model model) {
		ArrayList<Actor> list = WebUtil.getSessionUser().getActors();
		if(list.size() != 0){
			if(list.get(0).getId() == 1)
			model.addAttribute("reset", true);
		};
		return "welcome/workbench";
	}

	@SuppressWarnings("unused")
	private boolean checkMobile(String tel) {
		boolean flag = true;
		if (tel == null || "".equals(tel) || tel.length() != 11) {
			flag = false;
		}
		try {
			flag = Tool.isMobile(tel);
		} catch (Exception e) {
			LOGGER.error(StackTraceUtil.getStackTrace(e));
			flag = false;
		}
		return flag;
	}
}
